<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品显示</title>
    <link rel="stylesheet" href="../css/layui.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.10.4/dayjs.min.js"></script>
    <script src="../js/jquery-3.4.1.min.js" type="text/javascript"></script>
    <style type="text/css">
        .layui-table-view .layui-table tr{
            height: 100px;
        }
        .layui-table-view .layui-table tr .layui-table-cell{
            height: 50px;
            line-height: 50px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="root">
        <table class="layui-hide" id="test" lay-filter="test"></table>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm" lay-event="delByBatch">批量删除</button>
                <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
                <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
            </div>
        </script>

        <script type="text/html" id="barDemo">
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        </script>


        <script src="../js/layui.js" charset="utf-8"></script>
        <!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->

        <script>
            layui.use('table', function(){
                var table = layui.table;

                table.render({
                    elem: '#test'
                    ,url:'http://127.0.0.1:2021/shopstore/good/allgoods'
                    ,headers: {
                        'token': JSON.parse(localStorage.getItem('token')),
                        'userId': JSON.parse(localStorage.getItem('admin')).userId
                    }
                    ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                    ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                        title: '提示'
                        ,layEvent: 'LAYTABLE_TIPS'
                        ,icon: 'layui-icon-tips'
                    }]
                    ,title: '用户数据表'
                    ,cols: [[
                        {type: 'checkbox', fixed: 'left'}
                        ,{field:'goodName', title:'商品名', width:200, unresize: true}
                        ,{field:'goodPrice', title:'商品价格', width:150,unresize: true}
                        ,{field:'', title:'商品图片', width:150,  sort: true,unresize: true, templet: function(res){
                                return '<img width="50px" height="50px" src="data:image/jpeg;base64,'+res.imgBase64+'"/>'
                            }}
                        ,{field:'goodCreateTime', title:'入库时间', width:200,unresize: true,templet: (resp)=>{
                                return dayjs(resp.goodCreateTime).format('YYYY-MM-DD HH:mm:ss')
                            }}
                        ,{field:'goodSku', title:'唯一标识', width:200, sort: true,unresize: true}
                        ,{field:'goodSaler', title:'商家', width:200,unresize: true}
                        ,{field:'goodType', title:'商品分类', width:120}
                        ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
                    ]]
                    ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                        layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                        //,curr: 5 //设定初始在第 5 页
                        ,limit:5 //一页显示多少条
                        ,limits:[3,5,10]//每页条数的选择项
                        ,groups: 4 //只显示 2 个连续页码
                        ,first: "首页" //不显示首页
                        ,last: "尾页" //不显示尾页
                    }
                });

                //头工具栏事件
                table.on('toolbar(test)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    let idList = new Array();
                    switch(obj.event){
                        case 'delByBatch':
                            var data = checkStatus.data;
                            data.map((item,index)=>{
                                idList.push(item.goodId);
                            });
                            //批量删除
                            if(idList.length === 0){
                                layer.alert("请勾选之后在操作哦!");
                            }else{
                                layer.confirm("确认删除吗?",()=>{
                                    let list = JSON.stringify(idList)
                                    console.log(list);
                                    $.ajax({
                                        url:'http://127.0.0.1:2021/shopstore/good/deletebatchId',
                                        type:'post',
                                        data:{
                                            "list":list
                                        },
                                        headers: {
                                            'token': JSON.parse(localStorage.getItem('token')),
                                            'userId': JSON.parse(localStorage.getItem('admin')).userId
                                        },
                                        async: true,
                                        dataType: 'json',
                                        success:(resp)=>{
                                            //resp.status=true,删除成功
                                            if(resp.status){
                                                window.location.reload();
                                            }else{
                                                layer.alert("删除失败，请稍后再试");
                                            }
                                        }
                                    })
                                })
                            }
                            //layer.alert(JSON.stringify(idList));
                            break;
                        case 'getCheckLength':
                            var data = checkStatus.data;
                            layer.msg('选中了：'+ data.length + ' 个');
                            break;
                        case 'isAll':
                            layer.msg(checkStatus.isAll ? '全选': '未全选');
                            break;

                        //自定义头工具栏右侧图标 - 提示
                        case 'LAYTABLE_TIPS':
                            layer.alert('这是工具栏右侧自定义的一个图标按钮');
                            break;
                    };
                });

                //监听行工具事件
                table.on('tool(test)', function(obj){
                    var data = obj.data;
                    if(obj.event === 'del'){
                        layer.confirm('真的删除么', function(index){
                            //商品id
                            console.log(data.goodId)
                            //删除逻辑
                            $.ajax({
                                url: 'http://127.0.0.1:2021/shopstore/good/deleteById',
                                type: 'get',
                                data:{
                                  goodId:data.goodId
                                },
                                headers: {
                                    'token': JSON.parse(localStorage.getItem('token')),
                                    'userId': JSON.parse(localStorage.getItem('admin')).userId
                                },
                                async:true,
                                dataType:'json',
                                success:(resp)=>{
                                    if(resp.status){
                                        window.location.reload();
                                    }
                                },
                                error: (error)=>{
                                    console.log(error)
                                }
                            })
                            layer.close(index);
                        });
                    } else if(obj.event === 'edit'){
                        localStorage.setItem("imgPath",obj.data.goodImgPath)
                        sessionStorage.setItem('update_obj',JSON.stringify(obj.data));
                        window.location.href = 'update_good.html'
                    }
                });
            });
        </script>
    </div>
</body>
</html>